package com.example.hook.monitor;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.util.Scanner;

/**
 * JMX监控控制客户端 - 用于远程控制监控Agent
 */
public class MonitorControlClient {
    
    private MBeanServerConnection mbsc;
    private ObjectName objectName;
    
    public static void main(String[] args) {
        MonitorControlClient client = new MonitorControlClient();
        try {
            client.connect();
            client.runInteractiveSession();
        } catch (Exception e) {
            System.err.println("连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void connect() throws Exception {
        System.out.println("正在连接到监控Agent...");
        
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9998/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        mbsc = jmxc.getMBeanServerConnection();
        objectName = new ObjectName("com.example.hook:type=MonitorAgent");
        
        System.out.println("已连接到监控Agent");
    }
    
    private void runInteractiveSession() throws Exception {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("\n=== 监控控制客户端 ===");
        
        while (true) {
            System.out.println("\n请选择操作:");
            System.out.println("1. 启动监控");
            System.out.println("2. 停止监控");
            System.out.println("3. 查看监控状态");
            System.out.println("4. 查看统计信息");
            System.out.println("5. 重置统计");
            System.out.println("6. 启用/禁用时间追踪");
            System.out.println("7. 退出");
            System.out.print("请输入选择 (1-7): ");
            
            String choice = scanner.nextLine().trim();
            
            try {
                switch (choice) {
                    case "1":
                        startMonitoring();
                        break;
                    case "2":
                        stopMonitoring();
                        break;
                    case "3":
                        showStatus();
                        break;
                    case "4":
                        showStatistics();
                        break;
                    case "5":
                        resetStatistics();
                        break;
                    case "6":
                        toggleTimeTracking();
                        break;
                    case "7":
                        System.out.println("退出客户端");
                        return;
                    default:
                        System.out.println("无效选择，请重新输入");
                }
            } catch (Exception e) {
                System.err.println("操作失败: " + e.getMessage());
            }
        }
    }
    
    private void startMonitoring() throws Exception {
        mbsc.invoke(objectName, "startMonitoring", null, null);
        System.out.println("✅ 监控已启动");
    }
    
    private void stopMonitoring() throws Exception {
        mbsc.invoke(objectName, "stopMonitoring", null, null);
        System.out.println("⏹️ 监控已停止");
    }
    
    private void showStatus() throws Exception {
        Boolean isMonitoring = (Boolean) mbsc.getAttribute(objectName, "Monitoring");
        Boolean timeTracking = (Boolean) mbsc.getAttribute(objectName, "TimeTrackingEnabled");
        
        System.out.println("📊 监控状态:");
        System.out.println("  - 监控状态: " + (isMonitoring ? "🟢 运行中" : "🔴 已停止"));
        System.out.println("  - 时间追踪: " + (timeTracking ? "🟢 启用" : "🔴 禁用"));
    }
    
    private void showStatistics() throws Exception {
        Long callCount = (Long) mbsc.getAttribute(objectName, "CallCount");
        Long avgTime = (Long) mbsc.getAttribute(objectName, "AverageExecutionTime");
        
        System.out.println("📈 统计信息:");
        System.out.println("  - 方法调用次数: " + callCount);
        System.out.println("  - 平均执行时间: " + (avgTime / 1000000.0) + " ms");
    }
    
    private void resetStatistics() throws Exception {
        mbsc.invoke(objectName, "resetStatistics", null, null);
        System.out.println("🔄 统计信息已重置");
    }
    
    private void toggleTimeTracking() throws Exception {
        Boolean current = (Boolean) mbsc.getAttribute(objectName, "TimeTrackingEnabled");
        boolean newValue = !current;
        
        mbsc.invoke(objectName, "setTimeTrackingEnabled", 
                   new Object[]{newValue}, 
                   new String[]{boolean.class.getName()});
        
        System.out.println("⏱️ 时间追踪已" + (newValue ? "启用" : "禁用"));
    }
}